﻿// Less2DB.NET framework
// http://code.google.com/p/less2db/
//
// Copyright © Wangzhongwu, 2011
// alex.wzw@gmail.com
//

namespace Less2DB.SQLBuilder
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    /// <summary>
    /// 表示 SQL SELECT 查询构造器。
    /// </summary>
    class SQLSelectBuilder : BuilderBase
    {
        public SQLSelectBuilder(string tableName)
        {
            this.TableName = tableName;
        }

        private int _top;

        /// <summary>
        /// 获取或设置 SQL SELECT 查询的记录数。
        /// 该属性是一个差异标准，如果使用该属性必须设置 SQLSelectBuilder.QueryAssembly 属性，以实现不同的差异标准。
        /// </summary>
        public int Top
        {
            get { return _top; }
            set { _top = value; }
        }

        private SQLGroupBy _groupby = new SQLGroupBy();

        /// <summary>
        /// 构造 SQL SELECT 查询的分组条件。
        /// </summary>
        public SQLGroupBy GroupBy
        {
            get { return _groupby; }
        }

        private SQLOrderBy _orderby = new SQLOrderBy();

        /// <summary>
        /// 构造 SQL SELECT 查询的排序条件。
        /// </summary>
        public SQLOrderBy OrderBy
        {
            get { return _orderby; }
        }

        private string ToString(Less2DB.Interfaces.ISQLBuilder query, int top, string fields, string table, string where, string groupby, string order)
        {
            string querystring = "SELECT {FIELDS} FROM {TABLE} {WHERE} {GROUPBY} {ORDER}";

            querystring = querystring.Replace("{FIELDS}", fields);
            querystring = querystring.Replace("{TABLE}", table);
            querystring = querystring.Replace("{WHERE}", where);
            querystring = querystring.Replace("{GROUPBY}", groupby);
            querystring = querystring.Replace("{ORDER}", order);

            if (top > 0)
                return query.GenerateSQLTopQueryString(querystring, top);
            else
                return querystring;
        }

        /// <summary>
        /// 将此实例的值转换为 System.String。
        /// </summary>
        /// <returns>其值与此实例相同的字符串。</returns>
        public override string ToString()
        {
            var sb = new StringBuilder();

            foreach (string field in this.Fields)
            {
                if (sb.Length == 0)
                    sb.Append(field);
                else
                    sb.Append(", " + field);
            }

            string fields = sb.ToString();

            return this.ToString(this.DiffImplementation, this.Top, fields, this.TableName, this.Where, this.GroupBy.GroupByString, this.OrderBy.OrderByString);
        }
    }
}
